package com.jacksen.demo.view.badgeview;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.ColorFilter;
import android.graphics.Paint;
import android.graphics.drawable.Drawable;
import android.support.annotation.IntRange;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.TypedValue;
import android.view.Gravity;

/**
 * Created by jacksen
 * http://blog.csdn.net/maosidiaoxian/article/details/54091024
 */

public class BadgeDrawableWrapper extends Drawable {

    private Drawable originalDrawable;

    private Paint paint;

    private boolean showBadge;

    private int badgeGravity = Gravity.CENTER;

    // badge view radius
    private int badgeRadius;

    private BadgeDrawableWrapper(Context context, Drawable drawable) {
        this.originalDrawable = drawable;
        badgeRadius = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 5, context.getResources().getDisplayMetrics());
    }

    public static BadgeDrawableWrapper wrap(Context context, Drawable drawable) {
        if (drawable instanceof BadgeDrawableWrapper) {
            return (BadgeDrawableWrapper) drawable;
        }
        return new BadgeDrawableWrapper(context, drawable);
    }

    public void showBadgeView(boolean flag) {
        showBadge = flag;
        invalidateSelf();
    }

    /**
     * set the badge view's gravity
     *
     * @param gravity
     */
    public void setBadgeGravity(int gravity) {
        this.badgeGravity = gravity;
    }

    public void setBadgeRadius(int radius) {
        this.badgeRadius = radius;
    }

    @Override
    public void draw(@NonNull Canvas canvas) {
        originalDrawable.draw(canvas);

        if (showBadge) {
            int x = getBounds().right;
            int y = getBounds().top;

            if ((Gravity.LEFT & badgeGravity) == Gravity.LEFT) {
                x -= badgeRadius;
            } else if ((Gravity.RIGHT & badgeGravity) == Gravity.RIGHT) {
                x += badgeRadius;
            }

            if ((Gravity.TOP & badgeGravity) == Gravity.TOP) {
                y -= badgeRadius;
            } else if ((Gravity.BOTTOM & badgeGravity) == Gravity.BOTTOM) {
                y += badgeRadius;
            }

            canvas.drawCircle(x, y, badgeRadius, paint);
        }
    }

    @Override
    public void setAlpha(@IntRange(from = 0, to = 255) int alpha) {
        originalDrawable.setAlpha(alpha);
    }

    @Override
    public void setColorFilter(@Nullable ColorFilter colorFilter) {
        originalDrawable.setColorFilter(colorFilter);
    }

    @Override
    public int getOpacity() {
        return originalDrawable.getOpacity();
    }
}
